package com.zhiling.www.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zhiling.www.entity.Result;
import com.zhiling.www.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String filterType() {
        return "pre";//pre , 可以在请求被路由之前调用 ;  post, 之后
    }

    @Override
    public int filterOrder() {
        return 0;//fifilterOrder：通过 int 值来定义过滤器的执行顺序
    }

    @Override
    public boolean shouldFilter() {
        return true;
        /**
         * shouldFilter：返回一个 boolean 类型来判断该过滤器是否要执行，
         * 所以通过此函数可实现过滤器 的开关。在上例中，我们直接返回 true， 所以该过滤器总是生效
         */
    }

    //run：过滤器的具体逻辑
    @Override
    public Object run() throws ZuulException {
        RequestContext rc = RequestContext.getCurrentContext();//获取请求上下文；
        HttpServletRequest request = rc.getRequest();
        String uri = request.getRequestURI();
        if (uri.equals("/user/login") || uri.contains("/user/register")){
            return  null;   //首页、登录、注册 不拦截
        }
        if (uri.contains("/user/getCode")){
            return  null;   //获取验证码  不拦截
        }
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseToken(token);
        //用户身份证未验证，不能进行买入卖出操作
        if(uri.contains("/user/checkCard") || uri.contains("/stocktrading/buystock") || uri.contains("/stocktrading/sellstock")){
            String userState = String.valueOf(claims.get("userState"));
            if (userState.equals("0")){
                HttpServletResponse response = rc.getResponse();
                response.setContentType("text/html;charset=UTF-8");//设置响应字符编码格式！！！
                Result result = new Result();
                result.setCode(401); //身份证未验证；
                result.setMsg("您未实名认证！");
                try {
                    response.getWriter().print(JSON.toJSONString(result));
                } catch (IOException e) {
                }
                rc.setResponseStatusCode(200);
                //rc.setResponseBody("经过微服务网关后，发现你没有权限继续访问！！！");
                rc.setSendZuulResponse(false);//拦截
                return null;
            }

        }
        if (claims != null){
            String userId = String.valueOf(claims.get("userId"));
            String redisToken = (String) redisTemplate.opsForHash().get("user", userId+"");
            if (redisToken != null){
                return  null;    //未失效，未注销，不拦截
            }
        }
        HttpServletResponse response = rc.getResponse();
        response.setContentType("text/html;charset=UTF-8");//设置响应字符编码格式！！！
        Result result = new Result();
        result.setCode(403); //没有权限访问的错误码；
        result.setMsg("登录失效");
        try {
            response.getWriter().print(JSON.toJSONString(result));
        } catch (IOException e) {
        }
        rc.setResponseStatusCode(200);
        //rc.setResponseBody("经过微服务网关后，发现你没有权限继续访问！！！");
        rc.setSendZuulResponse(false);//拦截
        return null;
    }
}
